using System.Transactions;
using DealerPlatform.Domain;
using DealerPlatform.Service.OrderApp.Dtos;
using DealerPlatform.Service.ShoppingCartApp.Dtos;

namespace DealerPlatform.Service.OrderApp;

public partial class OrderService
{
    public async Task<string> AddOrder(string customerNo, OrderMasterInputDto input, List<ShoppingCartDto> carts)
    {
        using TransactionScope ts = new(TransactionScopeAsyncFlowOption.Enabled);
        try
        {
            // 添加主订单
            var inputDate = DateTime.Now;
            var orderNo = Guid.NewGuid().ToString();
            var master = new SaleOrderMaster()
            {
                CustomerNo = customerNo,
                DeliveryDate = input.DeliveryDate,
                EditUserNo = customerNo,
                InputDate = inputDate,
                Remark = input.Remark,
                InvoiceNo = input.Invoice,
                SaleOrderNo = orderNo,
                StockNo = ""
            };
            await saleOrderMasterRepository.InsertAsync(master);
            // 添加流程
            await AddProgress(orderNo, inputDate);
            // 添加订单详情
            await AddOrderDetail(carts, customerNo, orderNo, inputDate);
            // 提交事务
            ts.Complete();
            // 删除redis中的购物车的数据
            foreach (var cart in carts)
            {
                redisWorker.RemoveKey($"cart:{cart.CartGuid}:{customerNo}");
            }

            return orderNo;
        }
        catch (Exception e)
        {
            ts.Dispose();
            throw;
        }
    }
}